// 多站点后台脚本配置
const MULTI_SITE_CONFIG = {
  apiUrl: 'http://dev.com/multi-site-token-receiver.php',
  retryCount: 2,
  retryDelay: 3*1000, // 修改默认值为3秒
  lastSentTokens: new Map(), // 存储每个站点的最后发送的token
  lastExportTimes: new Map() // 存储每个站点的最后导出时间
};

// 配置加载状态
let configLoaded = false;

// 测试连接
async function testConnection(apiUrl = null) {
  const urlToTest = apiUrl || MULTI_SITE_CONFIG.apiUrl;
  
  try {
    const response = await fetch(urlToTest, {
      method: 'OPTIONS',
      headers: {
        'Content-Type': 'application/json',
      }
    });
    
    return { success: true, message: '连接正常' };
  } catch (error) {
    return { success: false, error: `连接失败: ${error.message}` };
  }
}

// 发送token到本地服务
async function sendTokenToServer(siteData) {
  try {
    const response = await fetch(MULTI_SITE_CONFIG.apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        siteName: siteData.siteName,
        siteDomain: siteData.siteDomain,
        authType: siteData.authType,
        authKey: siteData.authKey,
        token: siteData.token
      })
    });

    if (response.ok) {
      const result = await response.json();
      console.log('[Multi-Site Token Export] 服务器响应:', result);
      return { success: true, data: result };
    } else {
      const errorText = await response.text();
      throw new Error(`HTTP ${response.status}: ${response.statusText} - ${errorText}`);
    }
  } catch (error) {
    console.error('[Multi-Site Token Export] 发送token失败:', error);
    return { success: false, error: error.message };
  }
}

// 带重试的发送函数
async function sendTokenWithRetry(siteData, retryCount = MULTI_SITE_CONFIG.retryCount) {
  let lastError = null;
  
  for (let i = 0; i <= retryCount; i++) {
    const result = await sendTokenToServer(siteData);
    
    if (result.success) {
      return result;
    }
    
    lastError = result.error;
    
    if (i < retryCount) {
      console.log(`[Multi-Site Token Export] 重试 ${i + 1}/${retryCount}... (错误: ${lastError})`);
      await new Promise(resolve => setTimeout(resolve, MULTI_SITE_CONFIG.retryDelay));
    }
  }
  
  return { 
    success: false, 
    error: `重试次数已用完 (${retryCount + 1}次尝试)。最后错误: ${lastError}` 
  };
}

// 处理来自内容脚本的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'sendToken') {
    const siteDomain = message.siteDomain;
    const token = message.token;
    
    // 检查是否与上次发送的token相同
    if (token === MULTI_SITE_CONFIG.lastSentTokens.get(siteDomain)) {
      console.log(`[Multi-Site Token Export] 跳过重复的token (${message.siteName})`);
      // 即使跳过重复token，也要更新时间戳（因为用户刷新了页面，说明有新的访问）
      const timestamp = Date.now();
      MULTI_SITE_CONFIG.lastExportTimes.set(siteDomain, timestamp);
      console.log(`[Multi-Site Token Export] 更新重复token的时间戳:`, timestamp);
      console.log(`[Multi-Site Token Export] 使用的域名key:`, siteDomain);
      console.log(`[Multi-Site Token Export] 存储后的Map keys:`, Array.from(MULTI_SITE_CONFIG.lastExportTimes.keys()));
      sendResponse({ success: true, message: '跳过重复token' });
      return true;
    }
    
    // 发送token
    console.log(`[Multi-Site Token Export] 后台脚本开始处理Token发送 (${message.siteName})`);
    sendTokenWithRetry({
      siteName: message.siteName,
      siteDomain: message.siteDomain,
      authType: message.authType,
      authKey: message.authKey,
      token: message.token
    }).then(result => {
      console.log(`[Multi-Site Token Export] 后台脚本收到发送结果 (${message.siteName}):`, result);
      
      if (result.success) {
        MULTI_SITE_CONFIG.lastSentTokens.set(siteDomain, token);
        // 记录最后导出时间
        const timestamp = Date.now();
        MULTI_SITE_CONFIG.lastExportTimes.set(siteDomain, timestamp);
        console.log(`[Multi-Site Token Export] Token已成功发送并保存 (${message.siteName})`);
        console.log(`[Multi-Site Token Export] 最后导出时间已更新:`, timestamp);
        console.log(`[Multi-Site Token Export] 使用的域名key:`, siteDomain);
        console.log(`[Multi-Site Token Export] 存储后的Map keys:`, Array.from(MULTI_SITE_CONFIG.lastExportTimes.keys()));
        console.log(`[Multi-Site Token Export] 当前lastExportTimes Map:`, Array.from(MULTI_SITE_CONFIG.lastExportTimes.entries()));
      } else {
        console.log(`[Multi-Site Token Export] Token发送失败，未更新lastSentToken (${message.siteName})`);
      }
      
      console.log(`[Multi-Site Token Export] 后台脚本准备发送响应 (${message.siteName}):`, result);
      sendResponse(result);
    }).catch(error => {
      console.error(`[Multi-Site Token Export] 后台脚本处理Token时出错 (${message.siteName}):`, error);
      sendResponse({ success: false, error: error.message });
    });
    
    return true; // 保持消息通道开放
  }
  
  if (message.action === 'getStatus') {
    console.log('[Multi-Site Token Export] 收到getStatus请求');
    console.log('[Multi-Site Token Export] 配置加载状态:', configLoaded);
    
    // 直接从存储中获取所有配置，确保使用最新的配置
    chrome.storage.local.get(['sites', 'apiUrl', 'retryCount', 'retryDelay'], (result) => {
      console.log('[Multi-Site Token Export] storage.local.get结果:', result);
      
      const sites = result.sites || [];
      // 使用存储中的配置，如果没有则使用默认值
      const apiUrl = result.apiUrl || MULTI_SITE_CONFIG.apiUrl;
      const retryCount = result.retryCount !== undefined ? result.retryCount : MULTI_SITE_CONFIG.retryCount;
      const retryDelay = result.retryDelay !== undefined ? result.retryDelay : MULTI_SITE_CONFIG.retryDelay;
      
      console.log('[Multi-Site Token Export] 当前lastExportTimes:', MULTI_SITE_CONFIG.lastExportTimes);
      console.log('[Multi-Site Token Export] 当前sites:', sites);
      
      const status = {
        apiUrl: apiUrl,
        retryCount: retryCount,
        retryDelay: retryDelay,
        sites: sites.map(site => {
          const lastExportTime = MULTI_SITE_CONFIG.lastExportTimes.get(site.site_domain) || null;
          console.log(`[Multi-Site Token Export] 站点 ${site.site_domain} 的最后导出时间:`, lastExportTime);
          console.log(`[Multi-Site Token Export] 当前lastExportTimes Map keys:`, Array.from(MULTI_SITE_CONFIG.lastExportTimes.keys()));
          console.log(`[Multi-Site Token Export] 查找的key: ${site.site_domain}`);
          return {
            site_name: site.site_name,
            site_domain: site.site_domain,
            auth_type: site.auth_type,
            auth_key: site.auth_key,
            enabled: site.enabled,
            lastToken: MULTI_SITE_CONFIG.lastSentTokens.get(site.site_domain) ? 
                      MULTI_SITE_CONFIG.lastSentTokens.get(site.site_domain).substring(0, 10) + '...' : null,
            lastExportTime: lastExportTime
          };
        })
      };
      console.log('[Multi-Site Token Export] 发送状态响应:', status);
      sendResponse(status);
    });
    return true; // 保持消息通道开放
  }
  
  if (message.action === 'testConnection') {
    testConnection(message.apiUrl).then(result => {
      sendResponse(result);
    });
    return true;
  }

  if (message.action === 'updateConfig') {
    const config = message.config;
    MULTI_SITE_CONFIG.apiUrl = config.apiUrl;
    MULTI_SITE_CONFIG.retryCount = config.retryCount;
    MULTI_SITE_CONFIG.retryDelay = config.retryDelay;
    sendResponse({ success: true });
    return true;
  }

  if (message.action === 'refreshPopup') {
    // 这是一个通知消息，用于触发popup刷新
    console.log('[Multi-Site Token Export] 收到refreshPopup通知');
    sendResponse({ success: true });
    return true;
  }
});

// 从存储中加载配置
function loadConfigFromStorage() {
  console.log('[Multi-Site Token Export] 开始从存储加载配置');
  chrome.storage.local.get(['apiUrl', 'retryCount', 'retryDelay'], (result) => {
    console.log('[Multi-Site Token Export] 存储中的配置:', result);
    
    if (result.apiUrl) {
      MULTI_SITE_CONFIG.apiUrl = result.apiUrl;
      console.log('[Multi-Site Token Export] 更新API URL:', result.apiUrl);
    }
    if (result.retryCount !== undefined) {
      MULTI_SITE_CONFIG.retryCount = result.retryCount;
      console.log('[Multi-Site Token Export] 更新重试次数:', result.retryCount);
    }
    if (result.retryDelay !== undefined) {
      MULTI_SITE_CONFIG.retryDelay = result.retryDelay;
      console.log('[Multi-Site Token Export] 更新重试延迟:', result.retryDelay);
    }
    configLoaded = true;
    console.log('[Multi-Site Token Export] 已从存储加载配置:', MULTI_SITE_CONFIG);
    console.log('[Multi-Site Token Export] 配置加载状态设置为:', configLoaded);
  });
}

// 扩展安装时的初始化
chrome.runtime.onInstalled.addListener(() => {
  console.log('[Multi-Site Token Export] 扩展已安装，开始加载配置');
  loadConfigFromStorage();
});

// 扩展启动时的初始化
chrome.runtime.onStartup.addListener(() => {
  console.log('[Multi-Site Token Export] 扩展已启动，开始加载配置');
  loadConfigFromStorage();
});

// 立即加载配置（防止onInstalled/onStartup未触发）
console.log('[Multi-Site Token Export] Background脚本开始执行，立即加载配置');
loadConfigFromStorage(); 